﻿using System;
using System.Collections.Generic;

namespace Pretext.Arguments {
    public class ArgumentParser {

        const string SwitchPrefix = "/";

        const char VariableSwitchToken = 'v';
        const char VariableNameSeperator = ':';
        const char VariableAssignmentOperator = '=';

        public string[] Arguments { get; private set; }
        public List<Switch> Switches { get; private set; }

        public ArgumentParser(string[] args) {

            this.Arguments = args;

            this.Switches = new List<Switch>();

            Process();   

        }

        private void Process() {

            foreach (string argument in this.Arguments) {

                if (argument.StartsWith(SwitchPrefix)) {

                    char typeString = char.Parse(argument.Substring(1, 1));

                    if (typeString == VariableSwitchToken) {

                        int colonIndex = argument.IndexOf(VariableNameSeperator) + 1;
                        int equalsIndex = argument.IndexOf(VariableAssignmentOperator);

                        string variableName = null;
                        string variableValue = null;

                        if (equalsIndex > -1){
                            variableName = argument.Substring(colonIndex, equalsIndex - colonIndex);
                            variableValue = argument.Substring(equalsIndex + 1);

                            variableValue = variableValue.Trim('\"');

                        }
                            else
                            variableName = argument.Substring(colonIndex);

                        VariableSwitch s;
                        
                        if (string.IsNullOrEmpty(variableValue))
                            s = new VariableSwitch(variableName);
                        else
                            s = new VariableSwitch(variableName, variableValue);
                        
                        this.Switches.Add(s);
                    } else {
                        this.Switches.Add(new Switch(typeString));
                    }

                }

            }

        }

    }
}